import { ref, reactive } from 'vue'

export interface UserInfo {
  id?: string
  email: string
  nickName: string
  token?: string
}

// 创建单例状态
const isLoggedIn = ref(false)
const userInfo = reactive<UserInfo>({
  email: '',
  nickName: ''
})

const setUserInfo = (info: Partial<UserInfo>): void => {
  Object.assign(userInfo, info)
}
const getUserInfo = (): UserInfo => {
  return JSON.parse(localStorage.getItem('userInfo') || '{}')
}

const setLoginStatus = (status: boolean): void => {
  isLoggedIn.value = status
}

const login = (info: UserInfo): void => {
  setUserInfo(info)
  setLoginStatus(true)
  // 保存到localStorage
  localStorage.setItem('userInfo', JSON.stringify(info))
  localStorage.setItem('isLoggedIn', 'true')
}

const logout = (): void => {
  setUserInfo({ email: '', nickName: '' })
  setLoginStatus(false)
  // 清除localStorage
  localStorage.removeItem('userInfo')
  localStorage.removeItem('isLoggedIn')
}

const initFromStorage = (): void => {
  const storedUserInfo = localStorage.getItem('userInfo')
  const storedLoginStatus = localStorage.getItem('isLoggedIn')

  if (storedUserInfo && storedLoginStatus === 'true') {
    try {
      const parsedUserInfo = JSON.parse(storedUserInfo)
      setUserInfo(parsedUserInfo)
      setLoginStatus(true)
    } catch (error) {
      console.error('Failed to parse stored user info:', error)
      logout()
    }
  }
}

export const useUserStore = () => {
  return {
    isLoggedIn,
    userInfo,
    setUserInfo,
    setLoginStatus,
    login,
    logout,
    initFromStorage,
    getUserInfo
  }
}
